/*
 * @Autor: Shihh
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-08 16:31:46
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-09-06 09:49:33
 */


const Sequelize = require('sequelize')

module.exports = (sequelize, DataTypes) => {

	class tagImage extends Sequelize.Model {


		/**
		 * @author: xgq
		 * @description: 
		 * @param {type} 
		 * @return: 
		 */
		static async getImgIdsByTagId(tag_id) {
			var tags=await this.findAll({where:{tag_id},raw:true});
			var image_ids=[]
			for(var key in tags){
				image_ids.push(tags[key].image_id)
			}
			return image_ids
		}

		/**
		 * @author: Shihh
		 * @description: 获取标签列表
		 * @param {type} 
		 * @return: 
		 */
		static async getTagsList(params) {
			var querydata = [];
			var where = {}
			if (params.image_id != undefined && params.image_id != null) {
				where.image_id = params.image_id
			}
			if (params.tag_id != undefined && params.tag_id != null) {
				where.tag_id = params.tag_id
			}

			let condition = {
				//返回的字段
				attributes: ['id', 'image_id', 'tag_id', 'tag_name'],
			}
			condition.where = where
			querydata = await this.findAll(condition)
			return {
				"rows": querydata
			};
		}

		/**
		 * @author: Shihh
		 * @description: 新增标签与图片关系
		 * @param {type} 
		 * @return: 
		 */
		static async addTags(params) {
			return await this.create({
				image_id: params.id,
				tag_id: params.tagId,
				tag_name: params.name,
			}).then(re => {
				return true
			}).catch(err => {
				return false
			})
		}
		/**
		 * @author: Shihh
		 * @description: 根据IMGID获取Tag  复用getTagsList
		 * @param {type} 
		 * @return: 
		 */
		static async getTagByImgId(id) {
			// 根据图片id查找tagId
			let querydata = await this.findAll({attributes:['tag_id'],where:{image_id:id},raw:true})
			return querydata
		}

		/**
		 * @author: xgq
		 * @description: 删除单个标签
		 * @param {type} 
		 * @return: 
		 */
		static async deleteTag(pars) {
			let res = await this.destroy(pars)
			return res
		}
	}

	tagImage.init({
		id: {
			type: DataTypes.INTEGER,
			primaryKey: true,
			autoIncrement: true
		},
		image_id: {
			type: DataTypes.INTEGER
		},
		tag_id: {
			type: DataTypes.INTEGER
		},
		tag_name: {
			type: DataTypes.STRING(45)
		},
	}, {
		sequelize,
		modelName: 'tag_image_map',
		freezeTableName: true,
		timestamps: false
	});


	return tagImage;

}